package org.example.codeservce.controller;


import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.spring.application.ImageCaptchaApplication;
import cloud.tianai.captcha.spring.vo.CaptchaResponse;
import cloud.tianai.captcha.spring.vo.ImageCaptchaVO;
import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.novelweb.tool.http.Result;
import cn.novelweb.tool.upload.file.FileInfo;
import cn.novelweb.tool.upload.local.LocalUpload;
import cn.novelweb.tool.upload.local.pojo.UploadFileParam;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.example.codeservce.comm.ImageUtil;
import org.example.codeservce.comm.Q;
import org.example.codeservce.entity.Order;
import org.example.codeservce.entity.User;
import org.example.codeservce.entity.to.CheckDTO;
import org.example.codeservce.service.OrderService;
import org.example.codeservce.service.UserService;
import org.example.codeservce.util.EmailUtil;
import org.example.codeservce.util.PasswordEncryp;
import org.example.codeservce.util.ToolCoreUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * @author: Li Qing
 * @date: 2024/5/10 11:32
 * @description:
 */
@RestController
@Api("接口")
@Slf4j
public class QController
{
    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    @Autowired
    private ImageCaptchaApplication imageCaptchaApplication;

    /**
     * 源码分析接口
     *
     * @param file 源码文件
     * @param type 分析框架
     * @return
     */
    @PostMapping("/uploadCodeFile")
    public Q uploadCodeFile(
            @RequestParam("orderNo") @ApiParam("订单号") String orderNo,
            @RequestParam("fileName") @ApiParam("文件名称") String fileName,
            @RequestParam("filePath") @ApiParam("文件路径") String filePath,
            @RequestParam("type") @ApiParam("分析框架类型:1.spring-boot 2.spring-cloud") Integer type)
    {
        return orderService.uploadCodeFile(orderNo, fileName,filePath, type);
    }

    /**
     * 断点续传方式上传文件：用于大文件上传
     *
     * @param file   文件参数
     * @param request 请求    consumes = "multipart/*", headers = "content-type=multipart/form-data", produces = "application/json;charset=UTF-8"
     */
    @RequestMapping(value = "/breakpoint-upload", consumes = "multipart/*", headers = "content-type=multipart/form-data", produces = "application/json;charset=UTF-8")
    public Q breakpointResumeUpload(UploadFileParam file, HttpServletRequest request)
    {
          return ToolCoreUtil.getToolDescription(file, request);
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码的值
     * @param codeStr  验证码的盐值
     * @return
     */
    @PostMapping("/login")
    public Q login(
            @RequestParam("username") @ApiParam("用户名") String username,
            @RequestParam("password") @ApiParam("密码") String password
    )
    {
        return userService.login(username, password);
    }

    /**
     * 注册
     *
     * @param user    用户对象
     * @param code    验证码
     * @param codeStr 验证码盐值
     * @return
     */
    @PostMapping("/enroll")
    public Q enroll(
            @ApiParam("用户信息") User user,
            @RequestParam("code") @ApiParam("验证码值") String code,
            @RequestParam("codeStr") @ApiParam("验证码的盐值") String codeStr
    )
    {
        return userService.enroll(user, code, codeStr);
    }


    /**
     * 获取验证码
     */
    @PostMapping("/captcha")
    public CaptchaResponse<ImageCaptchaVO> captcha(HttpServletRequest request)
    {
        log.info(IPUtils.getClientIpAddress(request));
        System.out.println(IpUtil.getIp());
        // 1.生成滑块验证码(该数据返回给前端用于展示验证码数据)
        CaptchaResponse<ImageCaptchaVO> res1 = imageCaptchaApplication.generateCaptcha(CaptchaTypeConstant.SLIDER);
        return res1;
    }

    @PostMapping("/check")
    public ApiResponse<?> checkCaptcha(@RequestBody CheckDTO data,
            HttpServletRequest request)
    {
        ApiResponse<?> response = imageCaptchaApplication.matching(data.getId(), data.getData());
        if (response.isSuccess())
        {
            return ApiResponse.ofSuccess(Collections.singletonMap("id", data.getId()));
        }
        return response;
    }

    /**
     * 邮箱发送验证码
     */
    @GetMapping("/sendEmail")
    public Q sendEmail(@RequestParam("email") @ApiParam("邮箱") String email)
    {
        //断言判断参数非空
        assert email != null && !email.isEmpty() : "接收验证码邮箱不能为空!";
        String codeEncryption = EmailUtil.sendMail(email);
        return Q.ok().q("codeStr", codeEncryption);
    }

    /**
     * 创建订单并且拉取支付
     */
    @GetMapping("/builderPay")
    public Q builderPay()
    {
        return orderService.builderPay();
    }

    /**
     * 头像上传
     *
     * @param file
     * @return
     */
    @PostMapping("/img")
    public Q saveImg(@RequestParam("file") MultipartFile file)
    {
        String fileName = ImageUtil.PhotoCompression(file);
        return fileName != null ? Q.ok().put("fileName", fileName) : Q.error();
    }

    /**
     * 查询源码解析（成功过后才可以查看）
     *
     * @param orderNo
     * @return
     */
    @GetMapping("/infoCode")
    public Q infoCode(String orderNo)
    {
        return orderService.info(orderNo);
    }

    /**
     * 查询源码解析结果
     *
     * @param orderNo
     * @return
     */
    @GetMapping("/info")
    public Q info(String orderNo)
    {
        return Q.ok().put("order", orderService.getOne(new LambdaQueryWrapper<Order>()
                                                               .eq(Order::getOrderNo, orderNo)));
    }

    /**
     * 查询当前用户全部的订单
     */
    @GetMapping("/byUserGetOrder")
    public Q byUserGetOrder()
    {
        return Q.ok().put("order", orderService.byUserGetOrder());
    }


}
